package com.quantanetwork.esm.port;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.logging.Logger;

/**
* Company: QuantaNetwork BeiJing Ltd
* Author : 张彦龙
* DateTime: Nov 25, 2008  4:24:37 PM
*/
public class IdentifyMethod
{
	public static Logger logger = Logger.getLogger(IdentifyMethod.class.getName());
	private Socket socket;
	private String response = "";
	private BufferedReader is;
	private PrintWriter os;
	public static final int TCP = 0;
	public static final int UDP = 1;
	private String message = "help^M^J";
	private boolean error = false;

	public Portinfo indentify(String server, int port, String message, String type, int timeOut)
	{
		if (message == null)
		{
			message = getMessage();
		}
		Portinfo bean = null;
		if (type.equals("TCP"))
		{
			response = "trying TCP=\"" + message + "\"; no connection";
			try
			{
				socket = new Socket();
				socket.connect(new InetSocketAddress(server, port), 2000);
			}
			catch (Exception e)
			{
				response += "; " + e.toString();
				error = true;
			}
			if (!error)
			{
				try
				{
					is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					os = new PrintWriter(socket.getOutputStream(), true /* autoFlush */
					);
				}
				catch (IOException e)
				{
					response += "; IO problem; " + e.toString();
					error = true;
				}
				if (!error)
				{
					response = "sending TCP=\"" + message + "\"; no reply";
					try
					{
						os.println(message);
					}
					catch (Exception e)
					{
						response += ("; " + e.toString() + "=" + message);
					}
					try
					{
						response = "sending TCP=\"" + message + "\"; reply=" + is.readLine();
					}
					catch (IOException e)
					{
						response += "; " + e.toString();
					}
				}
			}
		}
		else
		{
			//UDP在研究
		}
		if (!this.error)
		{
			bean.setDesc(getResponse());
		}
		return bean;
	}

	public Socket getSocket()
	{
		return socket;
	}

	public void setSocket(Socket socket)
	{
		this.socket = socket;
	}

	public String getResponse()
	{
		return response;
	}

	public void setResponse(String response)
	{
		this.response = response;
	}

	public BufferedReader getIs()
	{
		return is;
	}

	public void setIs(BufferedReader is)
	{
		this.is = is;
	}

	public PrintWriter getOs()
	{
		return os;
	}

	public void setOs(PrintWriter os)
	{
		this.os = os;
	}

	public String getMessage()
	{
		return message;
	}

	public void setMessage(String message)
	{
		this.message = message;
	}

	public boolean isError()
	{
		return error;
	}

	public void setError(boolean error)
	{
		this.error = error;
	}
}
